/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package deti.es.ukni.rest;

import deti.es.persistence.account.AccountDoesNotExist;
import deti.es.persistence.account.AccountManagerRemote;
import deti.es.ukni.cm.persistence.DAOFactory;
import deti.es.ukni.persistence.entity.Band;
import deti.es.ukni.persistence.entity.Bandelement;
import java.util.List;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.GET;
import javax.ws.rs.Produces;
import javax.ws.rs.PathParam;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;

/**
 * REST Web Service
 *
 * @author eurico
 */

public class BandResourceByName {
    @Context
    private UriInfo context;

    /** Creates a new instance of BandResource */
    public BandResourceByName() {
    }

    /**
     * Retrieves representation of an instance of deti.es.ukni.rest.BandResource
     * @param name resource URI parameter
     * @return an instance of java.lang.String
     */
    @GET
    @Produces("text/plain")
    public String getText(@PathParam("name")
    String name) {

        // A band name is not unique so it can exist
        // more than one band with the same name.
        JSONArray bands = new JSONArray();

        List<Band> listband;
        AccountManagerRemote AMBean;
        AMBean = DAOFactory.getAccountManager();
        try {
             listband = AMBean.findBands(name);

        } catch (AccountDoesNotExist ex) {
            return bands.toJSONString();
        }

        for( Band b : listband ){
            JSONObject json = new JSONObject();
            JSONArray  elements = new JSONArray();

            json.put("name", b.getName());
            json.put("id", b.getIdband());
            json.put("desc", b.getDescription());
            json.put("bio", b.getBiography());
            json.put("formation", b.getFormed().toString() );
            json.put("followers", b.getAccountCollection().size() );

            for( Bandelement e : b.getBandelementCollection() ){
                JSONObject element = new JSONObject();
                element.put("name", e.getName());
                element.put("role", e.getRole());
                element.put("bio", e.getBiography());

                elements.add(element);
            }

            bands.add(json);
        }

        return bands.toJSONString();
    }
}
